<template>
  <div class="com-container">
    <div class="title">
      <span :style="comStyle">▎{{ title }}</span>
      <span class="iconfont title-icon" @click="isShowTitle = !isShowTitle" :style="comStyle">&#xe6eb;</span>
      <div class="select-con" v-for="item in titleArr" :key="item.key" v-show="isShowTitle" :style="comStyle">
        <div class="select-item" @click="handleSelect(item.key)">{{item.text}}</div>
      </div>
    </div>
    <div class="com-chart" id="trend"></div>
  </div>
</template>

<script>
import {onMounted, onBeforeUnmount, inject, reactive, ref, computed, watch} from 'vue'
import { getTrendData } from "@/service/getChartsData";
import { getThemeValue } from '@/utils/theme_utils'
import { useStore } from 'vuex'

export default {
  // eslint-disable-next-line vue/multi-word-component-names
  name: "Trend",
  computed:{
    selectTypes() {
      if (!this.titleArr){
        return []
      }else {
        return  this.titleArr.map((item) => {
          return item.key !== 'map'
        })
      }
    },

  },
  setup(){
    // 1. 接收Echarts
    let echarts = inject('echarts')
    let chartInstance = reactive({})
    // 2. 定义接收数据变量
    let chartDate = reactive([])
    let xData = reactive([])
    let yData = reactive([])
    let seriesArr = reactive([])
    let legendArr = reactive([])
    let titleFontSize = ref(null)
    let titleArr = reactive([
      { key: 'map', text: '地区销量趋势'},
      { key: 'seller', text: '商家销量趋势'},
      { key: 'commodity', text: '商品销量趋势'}
    ])
    let title = ref(titleArr[0].text)

    let isShowTitle = ref(false)
    let choiceType = ref('map')
    const store = useStore()
    let comStyle = computed(() => {
      return {
        fontSize:titleFontSize.value + 'px',
        color:getThemeValue(store.state.theme).titleColor
      }
    })

    function initChart() {
      chartInstance = echarts.init(document.querySelector("#trend"), store.state.theme)

      const initOption = {
        grid:{
          left:'3%',
          top:'35%',
          right:'4%',
          bottom:'1%',
          containLabel:true
        },
        tooltip:{
          trigger:'axis'
        },
        // 对图例进行定位
        legend:{
          left:20,
          top:'15%',
          icon:'circle' // 'circle'值为 设置图例为圆形图标
        },
        xAxis:{
          type:'category',
          boundaryGap: false //x轴是否与Y轴起点一致，默认为不一致true, false为一致
        },
        yAxis:{
          type:'value'
        }
      }
      chartInstance.setOption(initOption)
    }

    async function getChartData() {
      let {data:res} = await getTrendData()
      chartDate = res
    }

    function setChartData() {
      //半透明的颜色值
      const colorArr1 = [
        'rgba(11, 168, 44, 0.5)',
        'rgba(44, 110, 255, 0.5)',
        'rgba(22, 242, 217, 0.5)',
        'rgba(254, 33, 30, 0.5)',
        'rgba(250, 105, 0, 0.5)'
      ]

      //全透明颜色值
      const colorArr2 = [
        'rgba(11, 168, 44, 0)',
        'rgba(44, 110, 255, 0)',
        'rgba(22, 242, 217, 0)',
        'rgba(254, 33, 30, 0)',
        'rgba(250, 105, 0, 0)'
      ]

      xData = chartDate.common.month
      yData = chartDate[choiceType.value].data
      seriesArr = yData.map((item, index) => {
        return {
          name: item.name,
          type: 'line', //折线图
          data: item.data,
          stack: choiceType.value,// 数据是否有序排列
          areaStyle:{ // 折线图下区域颜色的设置
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              {
                offset: 0,
                color:colorArr1[index]
              },
              {
                offset: 1,
                color:colorArr2[index]
              }
            ])
          }
        }
      })
      // 图例数据
      legendArr = yData.map(item => item.name)
    }

    function updateChart() {
      setChartData()

      const updateOption = {
        xAxis: {
          data:xData
        },
        // 显示图例
        legend: {
          data:legendArr //图例数据，即每条折线图的name
        },
        series: seriesArr
      }
      chartInstance.setOption(updateOption)

      titleArr = computed(() => {
        return titleArr.key !== choiceType.value

      })

    }

    // 获取点击切换标题的key， 根据key值切换图表
    function handleSelect(key) {
      choiceType.value = key
      isShowTitle.value = !isShowTitle.value
      title.value = chartDate[key].title
      updateChart()
    }

    function screenAdapter() {
      titleFontSize.value = document.querySelector("#trend").offsetWidth / 100 * 3.6

      const adapterOption = {
        legend:{
          itemWidth: titleFontSize.value * 1.5,// 图例宽度
          itemHeight: titleFontSize.value * 1.5,// 图例高度
          itemGap: titleFontSize.value,// 图例间隙
          textStyle: { // 图例字体样式
            fontSize: titleFontSize.value / 1.5,  //图例字体大小
          }
        }
      }
      chartInstance.setOption(adapterOption)
      chartInstance.resize()

    }

    watch(() => store.state.theme, () => {
      //console.log('主题切换了')
      chartInstance.dispose()//销毁当前的图表
      initChart()//重新初始化图表对象
      updateChart()//更新图表的展示
      screenAdapter()//完成屏幕的适配
    })

    onMounted(() => {
     getChartData().then(() => {
       initChart()
       updateChart()
       screenAdapter()
     })
     window.addEventListener('resize',screenAdapter)
   })

    onBeforeUnmount(() => {
      window.removeEventListener('resize',screenAdapter)
    })

    return {
      handleSelect,
      screenAdapter,
      comStyle,
      titleArr,
      isShowTitle,
      title,
    }

  }
}
</script>

<style scoped lang="less">

 .title{
   position: absolute;
   left: 20px;
   top: 20px;
   z-index: 9;
   color: #ffffff;
   .title-icon{
     cursor:pointer;
   }
   .select-con{
     position: relative;
     left: 20px;

   }
 }

</style>